import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

ApplicationWindow {
    visible: true
    width: 1000
    height: 700
    title: qsTr("儿童成长助手")
    
    // 程序退出时检查
    onClosing: function(close) {
        // 检查是否有数据修改（技能树或身高记录）
        var skillModified = skillModel.dataModified
        var heightModified = heightRecordModel.hasDataModified()
        
        // 检查云同步配置是否有效
        var skillSyncValid = skillModel.cloudSyncValid
        var heightSyncValid = heightRecordModel.cloudSyncValid !== undefined ? heightRecordModel.cloudSyncValid : true  // 身高记录可能没有这个属性，默认为true
        
        if (skillModified || heightModified) {
            // 如果配置无效，直接退出，不进行比对
            if ((skillModified && !skillSyncValid) || (heightModified && !heightSyncValid)) {
                // 配置无效，直接退出
                console.log("云同步配置无效，跳过退出检查，直接退出")
                return  // 允许退出
            }
            
            close.accepted = false  // 阻止退出
            isExitCheckInProgress = true  // 设置退出检查标志
            exitCheckProgressDialog.open()  // 显示进度对话框
            
            // 记录哪些数据被修改了
            pendingSkillCheck = skillModified
            pendingHeightCheck = heightModified
            
            // 发起检查请求（如果数据被修改且配置有效）
            var checkCount = 0
            var completedCount = 0
            
            function handleCheckComplete() {
                completedCount++
                if (completedCount >= checkCount) {
                    // 所有检查完成，关闭进度对话框，显示选择对话框
                    exitCheckProgressDialog.close()
                    exitConflictDialog.open()
                }
            }
            
            if (skillModified && skillSyncValid) {
                checkCount++
                skillModel.checkAndSyncOnExit()
            } else if (skillModified) {
                // 配置无效，标记为已完成但不检查
                skillCheckCompleted = true
            }
            
            if (heightModified && heightSyncValid) {
                checkCount++
                heightRecordModel.checkAndSyncOnExit()
            } else if (heightModified) {
                // 配置无效，标记为已完成但不检查
                heightCheckCompleted = true
            }
            
            // 如果都没有修改，直接退出（这种情况不应该发生，但保险起见）
            if (checkCount === 0) {
                isExitCheckInProgress = false
                Qt.quit()
            } else {
                // 设置检查完成回调
                skillCheckCompleted = !skillModified || !skillSyncValid
                heightCheckCompleted = !heightModified || !heightSyncValid
            }
        }
        // 如果没有修改，直接退出
    }
    
    // 标志位：是否正在退出检查中
    property bool isExitCheckInProgress: false
    property bool pendingSkillCheck: false
    property bool pendingHeightCheck: false
    property bool skillCheckCompleted: false
    property bool heightCheckCompleted: false
    
    // 监听技能树云同步信号
    Connections {
        target: skillModel
        
        // 监听云端数据不同（启动时）
        function onCloudDataDifferent(cloudHash, localHash) {
            startupSkillDifferent = true
            checkStartupSyncStatus()
        }
        
        // 监听本地数据不同（退出时）
        function onLocalDataDifferent(localHash, cloudHash) {
            if (isExitCheckInProgress) {
                skillCheckCompleted = true
                skillNeedsSync = true
                checkExitSyncStatus()
            } else {
                // 正常切换Tab：显示本地冲突对话框
                localConflictDialog.open()
            }
        }
        
        // 监听检查失败（云端文件不存在等）
        function onSyncFailed(errorMsg) {
            if (isExitCheckInProgress) {
                skillCheckCompleted = true
                if (errorMsg.includes("不存在") || errorMsg.includes("404")) {
                    skillNeedsSync = true
                }
                checkExitSyncStatus()
            } else if (errorMsg.includes("云端文件不存在") && errorMsg.includes("是否要上传")) {
                // 启动时检测到云端文件不存在，提示用户上传
                cloudFileNotExistsDialog.open()
            } else if (errorMsg.includes("云同步配置无效")) {
                // 配置无效，不显示上传对话框，只记录日志
                console.log("云同步配置无效，已禁用所有云同步操作")
            }
        }
        
        // 监听数据一致信号（退出检查时）
        function onDataConsistent() {
            if (isExitCheckInProgress) {
                skillCheckCompleted = true
                skillNeedsSync = false
                checkExitSyncStatus()
            }
        }
    }
    
    // 监听身高记录云同步信号
    Connections {
        target: heightRecordModel
        
        // 监听云端数据不同（启动时）
        function onCloudDataDifferent(cloudHash, localHash) {
            startupHeightDifferent = true
            checkStartupSyncStatus()
        }
        
        // 监听本地数据不同（退出时）
        function onLocalDataDifferent(localHash, cloudHash) {
            if (isExitCheckInProgress) {
                heightCheckCompleted = true
                heightNeedsSync = true
                checkExitSyncStatus()
            }
        }
        
        // 监听检查失败（云端文件不存在等）
        function onSyncFailed(errorMsg) {
            if (isExitCheckInProgress) {
                heightCheckCompleted = true
                if (errorMsg.includes("不存在") || errorMsg.includes("404")) {
                    heightNeedsSync = true
                }
                checkExitSyncStatus()
            }
        }
        
        // 监听数据一致信号（退出检查时）
        function onDataConsistent() {
            if (isExitCheckInProgress) {
                heightCheckCompleted = true
                heightNeedsSync = false
                checkExitSyncStatus()
            }
        }
    }
    
    // 启动时同步状态
    property bool startupSkillDifferent: false
    property bool startupHeightDifferent: false
    
    // 退出时同步状态
    property bool skillNeedsSync: false
    property bool heightNeedsSync: false
    
    // 检查启动时同步状态
    function checkStartupSyncStatus() {
        // 如果两个检查都完成了，显示对话框
        if (startupSkillDifferent || startupHeightDifferent) {
            startupSyncDialog.open()
        }
    }
    
    // 检查退出时同步状态
    function checkExitSyncStatus() {
        // 如果两个检查都完成了
        if (skillCheckCompleted && heightCheckCompleted) {
            exitCheckProgressDialog.close()
            // 如果至少有一个需要同步，显示对话框
            if (skillNeedsSync || heightNeedsSync) {
                exitConflictDialog.open()
            } else {
                // 都不需要同步，直接退出
                isExitCheckInProgress = false
                Qt.quit()
            }
        }
    }

    // 垂直布局，左侧导航栏 + 右侧内容区
    RowLayout {
        anchors.fill: parent
        spacing: 0

        // ------------------------------------
        // 左侧：导航栏 (纵向排列)
        // ------------------------------------
        Rectangle {
            id: navBar
            Layout.fillHeight: true
            width: 200
            color: "#2C3E50" // 深色背景

            Column {
                anchors.fill: parent
                spacing: 5
                padding: 10

                // 顶部玩家信息面板
                Item {
                    width: parent.width - 20
                    height: 120
                    
                    PlayerProfilePanel {
                        id: playerPanel
                        anchors.centerIn: parent
                        width: parent.width
                        height: 100
                    }
                }

                // 导航按钮
                Rectangle {
                    id: skillTreeBtn
                    width: parent.width - 20
                    height: 50
                    color: currentTabIndex === 0 ? "#3498DB" : "#34495E"
                    radius: 8
                    border.color: "white"
                    border.width: 1
                    
                    Text {
                        anchors.centerIn: parent
                        text: "🌳 技能树"
                        color: "white"
                        font.pixelSize: 14
                        font.bold: true
                    }
                    
                    MouseArea {
                        anchors.fill: parent
                        onClicked: currentTabIndex = 0
                    }
                }

                Rectangle {
                    id: solarSystemBtn
                    width: parent.width - 20
                    height: 50
                    color: currentTabIndex === 1 ? "#3498DB" : "#34495E"
                    radius: 8
                    border.color: "white"
                    border.width: 1
                    
                    Text {
                        anchors.centerIn: parent
                        text: "🌞 太阳系"
                        color: "white"
                        font.pixelSize: 14
                        font.bold: true
                    }
                    
                    MouseArea {
                        anchors.fill: parent
                        onClicked: currentTabIndex = 1
                    }
                }

                Rectangle {
                    id: mountainBtn
                    width: parent.width - 20
                    height: 50
                    color: currentTabIndex === 2 ? "#3498DB" : "#34495E"
                    radius: 8
                    border.color: "white"
                    border.width: 1
                    
                    Text {
                        anchors.centerIn: parent
                        text: "🏔️ 每周一山"
                        color: "white"
                        font.pixelSize: 14
                        font.bold: true
                    }
                    
                    MouseArea {
                        anchors.fill: parent
                        onClicked: currentTabIndex = 2
                    }
                }

                Rectangle {
                    id: heightRecordBtn
                    width: parent.width - 20
                    height: 50
                    color: currentTabIndex === 3 ? "#3498DB" : "#34495E"
                    radius: 8
                    border.color: "white"
                    border.width: 1
                    
                    Text {
                        anchors.centerIn: parent
                        text: "📏 身高记录"
                        color: "white"
                        font.pixelSize: 14
                        font.bold: true
                    }
                    
                    MouseArea {
                        anchors.fill: parent
                        onClicked: currentTabIndex = 3
                    }
                }

                Rectangle {
                    width: parent.width - 20
                    height: 50
                    color: "#34495E"
                    radius: 8
                    border.color: "white"
                    border.width: 1
                    opacity: 0.5
                    
                    Text {
                        anchors.centerIn: parent
                        text: "设置"
                        color: "white"
                        font.pixelSize: 14
                    }
                }

                Rectangle {
                    width: parent.width - 20
                    height: 50
                    color: "#34495E"
                    radius: 8
                    border.color: "white"
                    border.width: 1
                    opacity: 0.5
                    
                    Text {
                        anchors.centerIn: parent
                        text: "帮助"
                        color: "white"
                        font.pixelSize: 14
                    }
                }
            }
        }

        // ------------------------------------
        // 右侧：内容区 (StackView)
        // ------------------------------------
        StackView {
            id: stackView
            Layout.fillWidth: true
            Layout.fillHeight: true
            initialItem: skillTreeView
        }
        
        // 技能树界面 (Tab 1)
        Loader {
            id: skillTreeView
            source: "qrc:/qml/SkillTreeView.qml"
            active: currentTabIndex === 0
            
            onActiveChanged: {
                // 当离开技能树界面时，检查是否需要上传
                if (!active) {
                    skillModel.checkAndSyncOnExit()
                }
            }
        }

        // 太阳系界面 (Tab 2)
        Loader {
            id: solarSystemView
            source: "qrc:/qml/SolarSystemView.qml"
            active: currentTabIndex === 1
        }

        // 每周一山界面 (Tab 3)
        Loader {
            id: mountainView
            source: "qrc:/qml/MountainView.qml"
            active: currentTabIndex === 2
        }

        // 身高记录界面 (Tab 4)
        Loader {
            id: heightRecordView
            source: "qrc:/qml/HeightRecordView.qml"
            active: currentTabIndex === 3
        }
    }
    
    // Tab切换逻辑
    property int currentTabIndex: 0
    
    onCurrentTabIndexChanged: {
        switch(currentTabIndex) {
            case 0: 
                stackView.replace(skillTreeView);
                break;
            case 1: 
                stackView.replace(solarSystemView);
                break;
            case 2: 
                stackView.replace(mountainView);
                break;
            case 3:
                stackView.replace(heightRecordView);
                break;
        }
    }
    
    // 启动时云端数据冲突对话框（支持可选同步）
    Dialog {
        id: startupSyncDialog
        title: "☁️ 云端数据同步"
        anchors.centerIn: parent
        width: 500
        height: 380
        modal: true
        
        background: Rectangle {
            color: "#FFF8E1"
            radius: 15
            border.color: "#FFA726"
            border.width: 3
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 15
            
            Text {
                text: "⚠️"
                font.pixelSize: 48
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "检测到云端数据与本地不同"
                font.pixelSize: 18
                font.bold: true
                color: "#F57C00"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "以下数据在云端有更新，是否从云端下载覆盖本地？\n\n⚠️ 警告：本地数据将被覆盖！"
                font.pixelSize: 14
                color: "#666666"
                width: parent.width
                wrapMode: Text.WordWrap
                horizontalAlignment: Text.AlignHCenter
            }
            
            // 可选同步复选框
            Column {
                width: parent.width
                spacing: 10
                
                CheckBox {
                    id: startupSkillCheckbox
                    text: "🌳 技能树数据"
                    checked: startupSkillDifferent
                    enabled: startupSkillDifferent
                    font.pixelSize: 14
                }
                
                CheckBox {
                    id: startupHeightCheckbox
                    text: "📏 身高测量数据"
                    checked: startupHeightDifferent
                    enabled: startupHeightDifferent
                    font.pixelSize: 14
                }
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Button {
                    text: "📥 从云端下载"
                    font.pixelSize: 15
                    enabled: startupSkillCheckbox.checked || startupHeightCheckbox.checked
                    
                    background: Rectangle {
                        radius: 20
                        color: parent.enabled ? (parent.pressed ? "#4CAF50" : "#66BB6A") : "#CCCCCC"
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: parent.enabled ? "white" : "#666666"
                        font: parent.font
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        startupSyncDialog.close()
                        
                        // 从云端下载技能树
                        if (startupSkillCheckbox.checked) {
                            skillModel.syncFromCloud()
                        }
                        
                        // 从云端下载身高记录
                        if (startupHeightCheckbox.checked) {
                            heightRecordModel.syncFromCloud()
                        }
                    }
                }
                
                Button {
                    text: "🚫 保留本地"
                    font.pixelSize: 15
                    onClicked: {
                        startupSyncDialog.close()
                        // 重置状态
                        startupSkillDifferent = false
                        startupHeightDifferent = false
                    }
                }
            }
        }
    }
    
    // 云端文件不存在提示对话框
    Dialog {
        id: cloudFileNotExistsDialog
        title: "☁️ 云端文件不存在"
        anchors.centerIn: parent
        width: 450
        height: 280
        modal: true
        
        background: Rectangle {
            color: "#E3F2FD"
            radius: 15
            border.color: "#2196F3"
            border.width: 3
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            Text {
                text: "📤"
                font.pixelSize: 48
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "云端文件不存在"
                font.pixelSize: 18
                font.bold: true
                color: "#1976D2"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "检测到云端没有技能树数据文件。\n是否要上传本地数据到云端？"
                font.pixelSize: 14
                color: "#666666"
                width: parent.width
                wrapMode: Text.WordWrap
                horizontalAlignment: Text.AlignHCenter
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Button {
                    id: uploadButton
                    text: "📤 上传到云端"
                    font.pixelSize: 15
                    
                    background: Rectangle {
                        radius: 20
                        gradient: Gradient {
                            GradientStop { position: 0.0; color: uploadButton.pressed ? "#1976D2" : "#2196F3" }
                            GradientStop { position: 1.0; color: uploadButton.pressed ? "#2196F3" : "#42A5F5" }
                        }
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font: parent.font
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        cloudFileNotExistsDialog.close()
                        skillModel.syncToCloud()
                    }
                }
                
                Button {
                    text: "稍后再说"
                    font.pixelSize: 15
                    onClicked: cloudFileNotExistsDialog.close()
                }
            }
        }
    }
    
    // 旧的云端数据冲突对话框（保留作为备用）
    Dialog {
        id: cloudConflictDialog
        title: "☁️ 云端数据冲突"
        anchors.centerIn: parent
        width: 450
        height: 280
        modal: true
        
        background: Rectangle {
            color: "#FFF8E1"
            radius: 15
            border.color: "#FFA726"
            border.width: 3
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            Text {
                text: "⚠️"
                font.pixelSize: 48
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "检测到云端数据与本地不同"
                font.pixelSize: 18
                font.bold: true
                color: "#F57C00"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "是否从云端下载数据覆盖本地？\n\n⚠️ 警告：本地数据将被覆盖！"
                font.pixelSize: 14
                color: "#666666"
                width: parent.width
                wrapMode: Text.WordWrap
                horizontalAlignment: Text.AlignHCenter
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Button {
                    text: "📥 从云端下载"
                    font.pixelSize: 15
                    
                    background: Rectangle {
                        radius: 20
                        color: parent.pressed ? "#4CAF50" : "#66BB6A"
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font: parent.font
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        cloudConflictDialog.close()
                        skillModel.syncFromCloud()
                    }
                }
                
                Button {
                    text: "🚫 保留本地"
                    font.pixelSize: 15
                    onClicked: cloudConflictDialog.close()
                }
            }
        }
    }
    
    // 本地数据冲突对话框（退出时）
    Dialog {
        id: localConflictDialog
        title: "💾 本地数据冲突"
        anchors.centerIn: parent
        width: 450
        height: 280
        modal: true
        
        background: Rectangle {
            color: "#E3F2FD"
            radius: 15
            border.color: "#42A5F5"
            border.width: 3
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            Text {
                text: "💾"
                font.pixelSize: 48
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "检测到本地数据已修改"
                font.pixelSize: 18
                font.bold: true
                color: "#1976D2"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "是否将本地数据上传到云端？\n\n⚠️ 提示：云端数据将被覆盖！"
                font.pixelSize: 14
                color: "#666666"
                width: parent.width
                wrapMode: Text.WordWrap
                horizontalAlignment: Text.AlignHCenter
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Button {
                    text: "☁️ 上传到云端"
                    font.pixelSize: 15
                    
                    background: Rectangle {
                        radius: 20
                        color: parent.pressed ? "#1976D2" : "#42A5F5"
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font: parent.font
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        localConflictDialog.close()
                        skillModel.syncToCloud()
                    }
                }
                
                Button {
                    text: "🚫 不上传"
                    font.pixelSize: 15
                    onClicked: {
                        localConflictDialog.close()
                        if (isExitCheckInProgress) {
                            // 如果是退出检查中取消上传，直接退出
                            isExitCheckInProgress = false
                            skillModel.clearModifiedFlag()  // 清除修改标志，避免循环弹窗
                            Qt.quit()
                        }
                    }
                }
            }
        }
    }
    
    // 退出检查进度对话框
    Dialog {
        id: exitCheckProgressDialog
        title: "⏳ 正在检查云端数据..."
        anchors.centerIn: parent
        width: 400
        height: 200
        modal: true
        closePolicy: Dialog.NoAutoClose  // 不允许手动关闭
        
        background: Rectangle {
            color: "#F5F5F5"
            radius: 15
            border.color: "#9E9E9E"
            border.width: 2
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            Text {
                text: "⏳"
                font.pixelSize: 48
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "正在比对本地和云端数据..."
                font.pixelSize: 16
                color: "#333333"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            // 简单的进度指示器
            Rectangle {
                width: parent.width * 0.8
                height: 10
                color: "#E0E0E0"
                radius: 5
                anchors.horizontalCenter: parent.horizontalCenter
                
                Rectangle {
                    id: progressBar
                    width: parent.width * 0.6
                    height: parent.height
                    color: "#42A5F5"
                    radius: 5
                    
                    SequentialAnimation on width {
                        loops: Animation.Infinite
                        NumberAnimation { from: 0; to: progressBar.parent.width * 0.6; duration: 1500 }
                        NumberAnimation { from: progressBar.parent.width * 0.6; to: 0; duration: 1500 }
                    }
                }
            }
        }
    }
    
    // 退出时数据冲突对话框（支持可选同步）
    Dialog {
        id: exitConflictDialog
        title: "💾 退出确认"
        anchors.centerIn: parent
        width: 500
        height: 380
        modal: true
        
        // 同步完成计数器
        property int exitSyncCompleted: 0
        property int exitSyncTotal: 0
        
        background: Rectangle {
            color: "#FFF3E0"
            radius: 15
            border.color: "#FF9800"
            border.width: 3
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 15
            
            Text {
                text: "⚠️"
                font.pixelSize: 48
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "检测到本地数据已修改"
                font.pixelSize: 18
                font.bold: true
                color: "#E65100"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "以下数据已修改，是否在退出前上传到云端？"
                font.pixelSize: 14
                color: "#666666"
                width: parent.width
                wrapMode: Text.WordWrap
                horizontalAlignment: Text.AlignHCenter
            }
            
            // 可选同步复选框
            Column {
                width: parent.width
                spacing: 10
                
                CheckBox {
                    id: skillSyncCheckbox
                    text: "🌳 技能树数据"
                    checked: skillNeedsSync
                    enabled: skillNeedsSync
                    font.pixelSize: 14
                }
                
                CheckBox {
                    id: heightSyncCheckbox
                    text: "📏 身高测量数据"
                    checked: heightNeedsSync
                    enabled: heightNeedsSync
                    font.pixelSize: 14
                }
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Button {
                    text: "☁️ 同步并退出"
                    font.pixelSize: 15
                    enabled: skillSyncCheckbox.checked || heightSyncCheckbox.checked
                    
                    background: Rectangle {
                        radius: 20
                        color: parent.enabled ? (parent.pressed ? "#FF6F00" : "#FF9800") : "#CCCCCC"
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: parent.enabled ? "white" : "#666666"
                        font: parent.font
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        exitConflictDialog.close()
                        
                        // 重置计数器
                        exitConflictDialog.exitSyncTotal = 0
                        exitConflictDialog.exitSyncCompleted = 0
                        
                        // 同步技能树
                        if (skillSyncCheckbox.checked) {
                            exitConflictDialog.exitSyncTotal++
                            skillModel.syncToCloud()
                        } else {
                            skillModel.clearModifiedFlag()
                        }
                        
                        // 同步身高记录
                        if (heightSyncCheckbox.checked) {
                            exitConflictDialog.exitSyncTotal++
                            heightRecordModel.syncToCloud()
                        } else {
                            heightRecordModel.clearModifiedFlag()
                        }
                        
                        // 如果都没有选择同步，直接退出
                        if (exitConflictDialog.exitSyncTotal === 0) {
                            isExitCheckInProgress = false
                            Qt.quit()
                        }
                    }
                }
                
                Button {
                    text: "🚫 不同步，直接退出"
                    font.pixelSize: 15
                    onClicked: {
                        exitConflictDialog.close()
                        isExitCheckInProgress = false
                        // 清除所有修改标志，避免循环弹窗
                        if (skillNeedsSync) {
                            skillModel.clearModifiedFlag()
                        }
                        if (heightNeedsSync) {
                            heightRecordModel.clearModifiedFlag()
                        }
                        Qt.quit()
                    }
                }
            }
        }
        
        // 监听上传成功信号
        Connections {
            id: exitSyncConnections
            enabled: false
            target: null
            
            function onSkillSyncSuccess(message) {
                if (isExitCheckInProgress && message.includes("云端")) {
                    skillModel.clearModifiedFlag()
                    checkExitSyncComplete()
                }
            }
            
            function onHeightSyncSuccess(message) {
                if (isExitCheckInProgress && message.includes("云端")) {
                    heightRecordModel.clearModifiedFlag()
                    checkExitSyncComplete()
                }
            }
            
            function checkExitSyncComplete() {
                // 检查是否所有同步都完成了
                if (!skillModel.dataModified && !heightRecordModel.hasDataModified()) {
                    isExitCheckInProgress = false
                    Qt.quit()
                }
            }
        }
        
        // 监听技能树同步成功（退出时）
        Connections {
            target: skillModel
            function onSyncSuccess(message) {
                if (isExitCheckInProgress && message.includes("云端")) {
                    skillModel.clearModifiedFlag()
                    // 如果是在退出对话框中触发的同步
                    if (exitConflictDialog.exitSyncTotal > 0) {
                        exitConflictDialog.exitSyncCompleted++
                        qDebug() << "技能树同步完成，已完成:" << exitConflictDialog.exitSyncCompleted << "/" << exitConflictDialog.exitSyncTotal
                        // 检查是否所有同步都完成了
                        if (exitConflictDialog.exitSyncCompleted >= exitConflictDialog.exitSyncTotal) {
                            qDebug() << "所有同步完成，准备退出"
                            isExitCheckInProgress = false
                            exitConflictDialog.exitSyncCompleted = 0
                            exitConflictDialog.exitSyncTotal = 0
                            Qt.quit()
                        }
                    } else {
                        // 如果不是在退出对话框中触发的同步，检查是否所有数据都已同步
                        // 如果技能树和身高记录都已同步完成，可以退出
                        if (!skillModel.dataModified && !heightRecordModel.hasDataModified()) {
                            qDebug() << "所有数据已同步，准备退出"
                            isExitCheckInProgress = false
                            Qt.quit()
                        }
                    }
                }
            }
        }
        
        // 监听身高记录同步成功（退出时）
        Connections {
            target: heightRecordModel
            function onSyncFinished() {
                if (isExitCheckInProgress) {
                    heightRecordModel.clearModifiedFlag()
                    // 如果是在退出对话框中触发的同步
                    if (exitConflictDialog.exitSyncTotal > 0) {
                        exitConflictDialog.exitSyncCompleted++
                        qDebug() << "身高记录同步完成，已完成:" << exitConflictDialog.exitSyncCompleted << "/" << exitConflictDialog.exitSyncTotal
                        // 检查是否所有同步都完成了
                        if (exitConflictDialog.exitSyncCompleted >= exitConflictDialog.exitSyncTotal) {
                            qDebug() << "所有同步完成，准备退出"
                            isExitCheckInProgress = false
                            exitConflictDialog.exitSyncCompleted = 0
                            exitConflictDialog.exitSyncTotal = 0
                            Qt.quit()
                        }
                    } else {
                        // 如果不是在退出对话框中触发的同步，检查是否所有数据都已同步
                        // 如果技能树和身高记录都已同步完成，可以退出
                        if (!skillModel.dataModified && !heightRecordModel.hasDataModified()) {
                            qDebug() << "所有数据已同步，准备退出"
                            isExitCheckInProgress = false
                            Qt.quit()
                        }
                    }
                }
            }
        }
    }
}
